package com.jspx.util;

import com.jspx.json.JSONArray;
import com.jspx.json.JSONException;
import com.jspx.json.JSONObject;
import com.jspx.utils.StringUtil;
import com.jspx.utils.XMLUtil;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by chenyuan on 2016-06-06.
 * 简单的对话留言
 */
public class ScopeNoteUtil {

    public static List<ScopeNote> decode(String xml)
    {
        if (xml.startsWith("<"))
        {
            ReadNotes readNotes = new ReadNotes();
            try {
                XMLUtil.parseXmlString(readNotes,xml);
                return readNotes.getNotes();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else if (!StringUtil.isNULL(xml)) {
            try {
                JSONArray array = new JSONArray(xml);
                List<ScopeNote> result = new LinkedList<ScopeNote>();
                for (int i=0;i<array.length();i++)
                {
                    JSONObject obj = (JSONObject)array.get(i);
                    ScopeNote note = new ScopeNote();
                    note.setIp(obj.getString("ip"));
                    note.setId(obj.getLong("id"));
                    note.setUid(obj.getLong("uid"));
                    note.setUserName(obj.getString("userName"));
                    note.setCreateDate(obj.getDate("createDate"));
                    note.setContent(obj.getString("cont"));
                    result.add(note);
                }
                return result;
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return new ArrayList<ScopeNote>();
    }

    public static String toXML(List<ScopeNote> notes) {
        StringBuilder sb = new StringBuilder();
        for (ScopeNote note : notes) {
            sb.append(note.toXML());
        }
        return XMLUtil.format(sb.toString());
    }

    public static String delete(String xml,long id) {
        List<ScopeNote> list = decode(xml);
        for (ScopeNote note:list)
        {
            if (note.getId()==id) list.remove(note);
        }
        return toXML(list);
    }

    public static List<ScopeNote> delete(List<ScopeNote> list,long id) {
        for (ScopeNote note:list)
        {
            if (note.getId()==id) list.remove(note);
        }
        return list;
    }

    public static String addNote(String xml,ScopeNote note)
    {
        List<ScopeNote> noteList = decode(xml);
        noteList.add(note);
        return ScopeNoteUtil.toXML(noteList);
    }

}
